#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Time       :   11:06
# Author     : Y4
# Site       : 验证前台 用户 是否登录和权限
# File       : valify_client_user.py
from flask import request, g

from App.common.client.get_client_user import get_user
from App.common.utils.util import rerep
from App.plugins import cache


def valify_login(fun):
    def wrapper(*args, **kwargs):
        token = request.args.get("token")
        if not token:
            return rerep(msg="你还没有登录,请登录", status=400)
        user_id = cache.get(token)
        if not user_id:
            return rerep(msg="帐号已过期,请重新登录", status=400)
        user = get_user(user_id)
        if not user:
            return rerep(msg="帐号已过期,请重新登录", status=400)
        g.user = user
        g.token = token
        return fun(*args, **kwargs)

    return wrapper


# 验证权限
def valify_permission(value):
    def wrapper_one(fun):
        def wrapper_two(*args, **kwargs):
            token = request.args.get("token")
            if not token:
                return rerep(msg="你还没有登录,请登录", status=400)
            user_id = cache.get(token)
            if not user_id:
                return rerep(msg="帐号已过期,请重新登录", status=400)
            user = get_user(user_id)
            if not user:
                return rerep(msg="帐号已过期,请重新登录", status=400)
            g.user = user
            g.token = token

            # 仅仅多了这一步传递参数来做哪些判断
            if not g.user.check_permission(value):
                return rerep(msg="没有操作权限,请联系客服", status=400)

            return fun(*args, **kwargs)

        return wrapper_two
    return wrapper_one